package util

import (
	"fmt"
	"os"
	"time"
)

var (
	myLoggerStruct *myLogger
	errLogsChan    = make(chan errLogInfo)
)

type myLogger struct{}

type errLogInfo struct {
	LogName   string
	BlockTag  string
	Level     int
	EventName string
	Errlog    string
}

// 初始化日志模块
func init() {
	myLoggerStruct = &myLogger{}
	go monitorErrLogsChan() // 启动异步日志通道处理协程
}

// 死循环监控日志通道，异步处理日志
func monitorErrLogsChan() {
	for {
		errLogInfo, ok := <-errLogsChan
		if !ok {
			// 通道已关闭，退出循环
			break
		}
		if errLogInfo.Level != 0 {
			WriteLogger(errLogInfo.BlockTag, errLogInfo.Level, errLogInfo.EventName, errLogInfo.Errlog, errLogInfo.LogName)
		}
	}
}

// 推送日志到日志通道
func PushErrLogsChan(level int, logName, blockTag, eventName, errlog string) {
	errLogsChan <- errLogInfo{
		LogName:   logName,
		BlockTag:  blockTag,
		Level:     level,
		EventName: eventName,
		Errlog:    errlog,
	}
}

// 获取当天日志文件名
func todayFileName() string {
	today := time.Now().Format("2006-01-02")
	return today + ".log"
}

// 创建日志文件
func NewLogFile(logName ...string) *os.File {
	fileName := todayFileName()
	if len(logName) > 0 {
		fileName = logName[0] + "_" + fileName
	}
	dirPath := "./temp/logs/" + logName[0] + "/"
	filePath := dirPath + fileName
	// 检查并创建目录
	if err := os.MkdirAll(dirPath, 0755); err != nil {
		panic(err)
	}

	file, err := os.OpenFile(filePath, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666)
	if err != nil {
		panic(err)
	}
	return file
}

// 写日志
func WriteLogger(blockTag string, level int, eventName, msg string, logName ...string) {
	levelStr := "info_level"
	switch level {
	case 1:
		levelStr = "info_level"
	case 2:
		levelStr = "warn_level"
	case 3:
		levelStr = "err_level"
	}

	logMsg := fmt.Sprintf("[%s] {\"block\":\"%s\",\"level\":\"%s\",\"event\":\"%s\",\"msg\":\"%s\"}\n", time.Now().Format("2006-01-02 15:04:05"), blockTag, levelStr, eventName, msg)

	logFile := NewLogFile(logName...)
	defer logFile.Close()

	if _, err := logFile.WriteString(logMsg); err != nil {
		panic(err)
	}
}
